package core

import (
	"encoding/json"
	cbase "findService/ss/servicebase"
	"jkgo/jk/jklog"

	l4g "github.com/alecthomas/log4go"
	imgp "jkgo/jkai/aiimage"
)

const (
	cmdBase      = "/" + serviceSelfName
	cmdImgDetect = "/" + serviceSelfName + "/imgdetect"
	cmdResponse  = "/" + serviceSelfName + "/response"
)

// ImgProcHandler defined for handler
type ImgProcHandler struct {
	iotclient *cbase.SSIoTClient
}

// NewSysClientIoT create one client IoT handler
func NewSysClientIoT(addr string, port int) (*ImgProcHandler, error) {
	l4g.Debug("New sys client of IoT [%s:%d]\n", addr, port)
	sys := &ImgProcHandler{}
	// create iotclient
	sys.iotclient, _ = cbase.NewSSIoTClient(addr, port, serviceSelfName)
	sys.iotclient.SetMsgHandle(sys)
	go sys.iotclient.Connect()

	return sys, nil
}

// IoTDealMessage MsgHandle interface
func (sc *ImgProcHandler) IoTDealMessage(topic, msg string) error {
	jklog.L().Debugln("topic ", topic, ", msg len ", len(msg))

	// imgdetect
	if topic == cmdImgDetect {
		mc := cbase.MsgPayload{}
		err := json.Unmarshal([]byte(msg), &mc)
		if err != nil {
			jklog.L().Errorln("Parse error ", err)
			return err
		}
		// mc.Data is a aiimage file
		ip := imgp.NewImgHandler([]byte(mc.Data))
		ip.SaveFile("/tmp/filetest.jpg")
		jklog.L().Debugln("pay load len = ", len(mc.Data))
		mc.Data = "Recv image done"
		str, _ := json.Marshal(mc)
		sc.iotclient.Pub(cmdResponse, string(str))
	} else {
		mc := cbase.MsgPayload{}
		err := json.Unmarshal([]byte(msg), &mc)
		if err != nil {
			mc.Data = "Data is invalid"
		} else {
			jklog.L().Debugln("payload is len = ", len(mc.Data))
			mc.Data = "Unsupported topic"
		}
		str, _ := json.Marshal(mc)
		sc.iotclient.Pub(cmdResponse, string(str))
	}

	return nil
}

// IoTStatusReport mqtt connected status report
func (sc *ImgProcHandler) IoTStatusReport(status string) {
	jklog.L().Infoln(serviceSelfName+" iot status change to ", status)
	if status == "connected" {
		subtopic := "/" + serviceSelfName + "/imgdetect"
		err := sc.iotclient.Sub(subtopic)
		if err != nil {
			jklog.L().Errorln("sub topic ", subtopic, " failed", err)
		}
	}
}
